""" Play a WAVE file. """

import pyaudio
import sys
import struct
import numpy as np

def play(data,
		width=2,
		channels=1,
		rate=16000):

	data = np.array(data, dtype='int16')
	chunk = 16000

	p = pyaudio.PyAudio()

	# open stream
	stream = p.open(format = p.get_format_from_width(width),
			channels = 1,
			rate = rate,
			output = True)

	# play stream
	for i in xrange(len(data)/chunk+1):
#		stream.write(data[i*chunk:(i+1)*chunk])
		if (i + 1) * chunk < len(data):
			stream.write(struct.pack('h' * chunk, *data[i*chunk:(i+1)*chunk]))
		else:
			stream.write(struct.pack('h' * len(data[i*chunk:(i+1)*chunk]), *data[i*chunk:(i+1)*chunk]))

	stream.close()
	p.terminate()
